package com.study.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alimt.model.v20181012.TranslateGeneralRequest;
import com.aliyuncs.alimt.model.v20181012.TranslateGeneralResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.study.common.constant.LocalConstant;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: 阿里机器翻译工具
 * @author: LChuang
 * @date: 2023/9/18 11:00
 */
@Slf4j
public class AliTranslateUtil {

    private static final DefaultProfile profile;

    private static final IAcsClient client;

    private static final TranslateGeneralRequest request;

    static {
        profile = DefaultProfile.getProfile(LocalConstant.REGION_ID, LocalConstant.ACCESS_KEY_ID, LocalConstant.ACCESS_KEY_SECRET);
        client = new DefaultAcsClient(profile);
        request = new TranslateGeneralRequest();
        request.setRegionId("cn-hangzhou");
        request.setFormatType("text");
        request.setSourceLanguage("zh");// 原语言
        request.setTargetLanguage("en");// 目标语言
        request.setScene("general");
    }

    public static String aliTranslate(String content) {
        try {
            request.setSourceText(content);
            TranslateGeneralResponse response = client.getAcsResponse(request);
            TranslateGeneralResponse.Data data = response.getData();
            // 去除特殊字符后返回
            return LcStrUtil.handleSpecialCharacter(data.getTranslated());
        } catch (ClientException e) {
            log.error("阿里云翻译异常：{}，翻译文本：{}", e.getMessage(), content);
        }
        return "";
    }


    public static void main(String[] args) {
        String text = "订单号";
        request.setSourceText(text);
        try {
            TranslateGeneralResponse response = client.getAcsResponse(request);
            TranslateGeneralResponse.Data data = response.getData();
            String translated = data.getTranslated();
            System.out.println(translated);
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
